﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using Google.GData.Documents;
using Google.GData.Client;
using Google.Documents;

namespace ResxLocalizationEditor.GoogleImport {
    public partial class FolderVisualizer : UserControl {
        public FolderVisualizer() {
            InitializeComponent();
        }

        delegate void GuiAction();

        public void LoadFolders(string username, string password) {
            listFolders.Items.Clear();
            listFolders.Enabled = false;
            ImportButton.Enabled = false;

            ThreadPool.QueueUserWorkItem(new WaitCallback((o) => {
                try {
                    var settings = new RequestSettings(GoogleDocsImport.ApiAppKey, username, password);
                    settings.AutoPaging = true;

                    var request = new DocumentsRequest(settings);
                    var feed = request.GetFolders();
                    var folders = feed.Entries.ToList(); //this executes the query

                    Invoke(new GuiAction(() => {
                        foreach (var folder in folders) {
                            var lvi = new ListViewItem(folder.Title);
                            lvi.SubItems.Add(folder.Updated.ToString());
                            lvi.Tag = folder;

                            listFolders.Items.Add(lvi);
                        }
                        listFolders.Enabled = true;
                    }));
                }
                catch (Exception ex) {
                    MessageBox.Show("Failed to retrieve folders: " + ex.ToString());
                }
            }));
        }

        private void FolderList_selectionChange(object sender, EventArgs e) {
            ImportButton.Enabled = (listFolders.SelectedItems.Count == 1);
        }

        public Document SelectedDocument {
            get {
                if (listFolders.SelectedItems.Count != 1) {
                    return null;
                }

                return listFolders.SelectedItems[0].Tag as Document;
            }
        }

    }
}
